package net.mikoo.seals.api.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import net.mikoo.seals.api.model.ResultType;
import net.mikoo.seals.api.model.upload.UploadRequest;
import net.mikoo.seals.api.model.upload.UploadResponse;
import net.mikoo.seals.api.utility.PartyUtility;
import net.mikoo.seals.biz.service.UpfileServices;
import net.mikoo.seals.model.Party;
import net.mikoo.seals.model.Upfile;
import net.mikoo.seals.utils.IPUtil;

@RequestMapping
@Controller
public class UploadController {

	private static Logger logger = LoggerFactory.getLogger(UploadController.class);
	
	@Autowired
	private UpfileServices upfileServices;
	
	@RequestMapping("/common/fileupload")
	@ResponseBody
	public UploadResponse fileupload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) {
		UploadResponse result = new UploadResponse();
		
		try {
			Long companyId = PartyUtility.getCurrentPartyCompanyId(request);
			Party party = PartyUtility.getCurrentParty(request);
			Upfile upfile = new Upfile();
			upfile.setFile(file);
			upfile.setCompanyId(companyId);
			upfile.setPartyId(party.getPartyId());
			upfile.setUploadIp(IPUtil.getRemoteAddr(request));
			upfile.setUploadTime(new Date());
			upfile.setModule("xiaochengxu");
			upfile = upfileServices.upload(upfile);

			result.setId(upfile.getUpfileId());
			result.setUrl(upfile.getFileUrl());
			result.setResult(ResultType.SUCCESS.getValue());;
		} catch (Exception e) {
			logger.error("", e);
			result.setResult(ResultType.ERROR.getValue());
		}
		return result;
	}
}
